<template>

  <div ref="loginForm"
       :model="loginForm">
    <div v-if="status==='show_list'">
      <div class="row"
           v-for="state in tableData" :key="state.i">
        <div class="col-md-12">
          <transition name='fade'>
              <div class="grid-content"
                   ref="liCon" style="height: 100%;width: 100%;"
              >
                <stats-card class="posts">
                  <div class="numbers" slot="content" style="height: auto;width: 160%" v-on:click="viewContent(state)">
                    <div>{{state.title}}</div>
                    <p>{{state.content}}</p>
                  </div>
                  <div class="stats" slot="footer">
                    <div style="float:left;"><i class="ti-user"></i> {{state.username}} &nbsp;&nbsp;
                      <i v-on:click="handleDeleteData(state)"><i class= "ti-trash"></i>delete</i>
                      &nbsp;&nbsp; tags: <i v-for="tag in state.tags"> {{ tag }} </i>
                    </div>
                    <div style="float:right;">time: {{state.time}}</div>
                  </div>
                </stats-card>
              </div>
          </transition>
        </div>
      </div>
    </div>
    <div v-if="status==='show_reply'">
      <div class="row">
        <div class="col-md-12">
          <transition name='fade'>
              <card class="post_content">
                <template slot="header">
                  <div class="replyReturn">
                  <div class="ti-back-left" v-bind:style="replyReturnStyle"
                       v-on:click="returnToPosts()"></div>
                  </div>
                  <h4 class="card-title">{{ postHead.title }}</h4>
                  <p class="card-category">Created by {{postHead.author}}</p>
                </template>
                <div class="headContents">
                  <div class="line">
                    <p>
                      {{postHead.content}}
                    </p>
                  </div>
                </div>
                <br />
                <div class="replys">
                  <div class="typo-line" v-for="reply in postData">
                    <span class="category">{{reply.username}}</span>
                    <p>
                      {{reply.content}}
                    </p>
                  </div>
                </div>
              </card>
          </transition>
          <div style="position: fixed;bottom: 40px;z-index: 10;width: 80%">
            <el-row :gutter="20">
              <el-col :span="20" >
                <el-input
                  type="textarea"
                  autosize
                  placeholder="请输入回复内容"
                  name="title"
                  v-model="replyContent"
                  :autosize="{ minRows: 2, maxRows: 4}"
                  autocomplete="on">
                </el-input>
              </el-col>
              <el-col :span="4">
                <el-button
                  @click.native.prevent="handlePostReply()"
                >发送</el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { StatsCard, ChartCard } from "@/components/index";
import Chartist from 'chartist';
export default {
  components: {
    StatsCard,
    ChartCard
  },
  /**
   * Chart data used to render stats, charts. Should be replaced with server data
   */
  computed: {
    postDataType() {
      return this.$store.state.postDataType;
    },
    list() {
      return this.$data.tempPostList;
    },
  },
  watch: {
    async postDataType() {
      this.ReloadPage();
    },
    async list() {
      for (let i=0; i < this.$data.tempPostList.length; i++) {
        await this.handleGetData(this.$data.tempPostList[i], i);
        //this.$data.tableData[i].index = i;
      }
    }
  },
  created() {
    //alert("created");
    //this.$message.error("1234");
  },
  mounted() {
    //alert("dashboard refresh");

    this.setSignature();

    window.addEventListener("scroll",this.setreplyReturnFix);
    //window.addEventListener("beforeunload", this.ReloadPage);
    this.ReloadPage();
  },
  destroyed() {
    window.removeEventListener('scroll', this.setreplyReturnFix);
  },
  methods: {
    setSignature() {
      //alert(this.$store.state.signature)
      this.$data.loginForm.signature = this.$store.state.signature;
      //alert(this.$data.loginForm.signature)
    },
    async ReloadPage() {
      //alert("reload page");
      if (this.$store.state.postDataType === "hot") {
        //alert("hot");
        //this.handleGetTimeEarlistData();
        await this.handleGetHotData();
      } else if (this.$store.state.postDataType === "timeLatest"){
        //alert("timeLatest");
        await this.handleGetTimeLatestData();
      } else if (this.$store.state.postDataType === "timeEarlist"){
        //alert("timeEarlist");
        await this.handleGetTimeEarlistData();
      }
      await this.$forceUpdate()
      //alert("after reload page")
    },
    setreplyReturnFix() {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 90) {
        this.$data.replyReturnStyle.top = 30 + "px";
      } else {
        this.$data.replyReturnStyle.top = 120 - scrollTop + "px";
      }
    },
    handleClick(row) {
      console.log(row);
    },
    showDialog(row) {
      this.handlingRow = row;
      this.loginForm.tempData.title = row.title;
      this.loginForm.tempData.username = row.username;
      this.loginForm.tempData.content = row.content;
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    async handleGetData(pid, i=0) {
      //alert("getdata");
          this.loading = true;
          await this.$store
            .dispatch("GetData", pid)
            .then(response => {
              this.loading = false;
              let code = response.data.status;
              if (code == "success") {
                let saveData = {}
                saveData.pid = response.data.pid;
                saveData.time = response.data.time;
                saveData.username = "host";
                saveData.title = response.data.title;
                saveData.content = response.data.content;
                saveData.dialogVisible = true;
                //saveData.index = i;
                saveData.tags = response.data.tags;
                this.$data.tableData.push(saveData);
              } else {
                this.$router.push({
                  path: "/error",
                  query: {message: response.data.message}
                });
              }
            })
            .catch(() => {
              this.loading = false;
            });
    },
    async handlePostNote() {
          this.loading = true;
          this.$store
            .dispatch("PostNote", this.loginForm)
            .then(response => {
              this.loading = false;
              //let code = response.status;
              if (response.data.status === "success") {
                let saveData = {}
                saveData.pid = response.data.pid;
                saveData.time = response.data.time;
                saveData.username = this.loginForm.username;
                saveData.title = this.loginForm.title;
                saveData.content = this.loginForm.content;
                saveData.dialogVisible = true;
                this.$data.tableData.push(saveData);
              } else {
                this.$router.push({
                  path: "/error",
                  query: {message: response.data.message}
                });
              }
            })
            .catch(() => {
              this.loading = false;
            });
    },
    async handleDeleteData(state) {
      this.loading = true;
      this.$store
          .dispatch("GetSign", this.loginForm)
          .then(response => {
            this.loading = false;
            let code = response.data.status;
            if (code === "success") {
              this.loginForm.signature = response.data.signature
              //this.$data.tableData.push(response.data.data)
            } else {
              alert("You can't delete that post")
            }
          })
          .catch(() => {
            this.loading = false;
          });
      this.loginForm.deletepid = state.pid;
          this.loading = true;
          this.$store
            .dispatch("DeleteData", this.loginForm)
            .then(response => {
              this.loading = false;
              let code = response.data.status;
              if (code === "success") {
                for (var i = 0; i < this.tableData.length; i++) {
                  if (this.tableData[i].pid === state.pid) {
                    this.tableData.splice(i, 1);
                  }
                }
                //this.$data.tableData.push(response.data.data)
              } else {
                alert("You can't delete that post")
              }
            })
            .catch(() => {
              this.loading = false;
            });
    },
    async handleGetTimeLatestData() {
      //alert("latest data")
      this.$data.tableData = [];
      this.loading = true;
      this.$store
        .dispatch("GetTimeData", "get_latest")
        .then(response => {
          this.loading = false;
          //let code = response.status;
          if (response.data.status === "success") {
            this.getPostList(response.data.pid + 1, "true")
            //this.handleGetData(response.data.pid, 0);
          } else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }
        })
        .catch(() => {
          this.loading = false;
        });

      //location.reload();
    },
    async getPostList(pid, front) {
      //alert(" "+pid + front)
      this.loading = true;
      this.$store
        .dispatch("GetPostList", {pid, front})
        .then(response => {
          this.loading = false;
          //this.$data.tableData = [];
          //let code = response.status;
          this.$data.tempPostList = response.data
        })
        .catch(() => {
          this.loading = false;
        });
    },
    async handleGetTimeEarlistData() {
      this.$data.tableData = [];
      this.loading = true;
      this.$store
        .dispatch("GetTimeData", "get_earliest")
        .then(response => {
          this.loading = false;
          //let code = response.status;
          if (response.data.status === "success") {
             this.$data.tempPid= response.data.pid - 1
            this.getPostList(this.$data.tempPid, "false")
            //this.handleGetData(response.data.pid, 0);
          //alert("stop handlegetdata")
          } else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }
          //alert("catch befor loding")
        })
        .catch(() => {
          this.loading = false;
        });
      this.$forceUpdate()
      //location.reload();
    },
    async handleGetHotData() {
      this.loading = true;
      this.$store
        .dispatch("GetHotData", this.loginForm)
        .then(response => {
          this.loading = false;
          this.$data.tableData = [];
          //let code = response.status;
          if (response.data.status === "success") {
            for (var i=0; i < response.data.pid_list.length; i++) {
              this.handleGetData(response.data.pid_list[i], i);
              //this.$data.tableData[i].index = i;
            }
          } else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }
        })
        .catch(() => {
          this.loading = false;
        });
      this.reload();
    },
    async handleGetReply(pid, rid) {
      await this.$store
        .dispatch("GetReply", [pid, rid])
        .then(response => {
          this.loading = false;
          if (response.data.status === "success") {
            let saveData = {}
            saveData.username = response.data.name,
            saveData.content = response.data.content,
            this.$data.postData.push(saveData);
          } else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handlePostReply() {
      //alert(this.$data.currentState.pid+this.$data.loginForm.signature+this.$data.replyContent)

      this.loading = true;
      this.$store
        .dispatch("PostReply", [this.$data.currentState.pid, this.loginForm.signature, this.$data.replyContent])
        .then(response => {
          this.loading = false;
          //let code = response.status;
          if (response.data.status === "success") {
            this.viewContent(this.$data.currentState)
          }/* else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }*/
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleGetEarlyReplyId(pid) {
      //alert("get earlt replyid")
      this.$store
        .dispatch("GetEarlyReplyId", pid)
        .then(response => {
          this.loading = false;
          if (response.data.status === "success") {
            //alert("resp rid"+response.data.rid)
            this.$data.rid = response.data.rid;
            //alert(""+response.data.rid)
          } else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    viewContent(state) {
      this.$data.currentState = state;
      for (var i = 0; i < this.$data.tableData.length;i++) {
        this.$data.tableData[i].dialogVisible = false;
      }
      this.$data.returnPosition = window.pageYOffset;
      window.scroll(0, -window.pageYOffset);
      //state.dialogVisible = true;
      this.$data.postHead.title = state.title;
      this.$data.postHead.author = state.username;
      this.$data.postHead.content = state.content;
      this.$data.status = 'show_reply';
      this.$data.replyPid = state.pid;
      this.$data.postData = [];
      this.handleGetEarlyReplyId(state.pid);
      //alert("out rid "+this.$data.rid)
      let temppac = {
        pid: state.pid,
        rid: this.$data.rid
      }
      this.$store
        .dispatch("GetReplyList", temppac)
        .then(async response => {
          this.loading = false;
          //this.$data.tableData = [];
          //let code = response.status;
          // eslint-disable-next-line no-constant-condition
          if (true) {
            for (var i=0; i < response.data.length; i++) {
              await this.handleGetReply(state.pid, response.data[i]);
              //this.$data.tableData[i].index = i;
            }
          } else {
            this.$router.push({
              path: "/error",
              query: {message: response.data.message}
            });
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    returnToPosts() {
      for (var i = 0; i < this.$data.tableData.length;i++) {
        this.$data.tableData[i].dialogVisible = true;
      }
      //window.pageYOffset = this.$data.returnPosition;
      window.scroll(0, this.$data.returnPosition);
      this.$data.status = 'show_list';
    },

  },

  data() {
    return {
      tempPid: 0,
      currentState: {},
      tempPostList: [],
      rid: 0,
      status: 'show_list',
      postData: [

      ],
      postHead:{},
      returnPosition: 0,
      input: '',
      tableData: [],
      loginForm: {
        search:"",
        username: "admin",
        signature:"",
        title: "",
        content:"",
        pid:"",
        time:"",
        deletepid:"",
        tempData:{
          pid:"",
          title:"",
          username: "",
          content: "",

        },
      },
      dialogVisible:false,
      fullscreen:false,
      handlingRow:0,
      replyContent: "",
      replyReturnHight:50,
      replyReturnStyle: {
        position: "fixed",
        top: "120px",
        right: '50px',
        float: "right",
      },
    }
  }
};
</script>
<style>
[v-cloak] {
  display: none;
}
.grid-content {
  color: #555;
  font-size: 14px;
  cursor: pointer;  /*鼠标悬停变小手*/
  width: 100%;
  height: auto;
  overflow: hidden;
  transition: height .3s;
}

.fade-enter{
  opacity: 0;
}
.fade-enter-active{
  transition: opacity 0.5s;
}
.fade-leave-to{
  opacity: 0;
}
.fade-leave-active{
  transition: opacity 0.5s;
}

/*.newslist ul li p {
  font-size: 14px;
  color: #555;
  line-height: 25px;
  height: 50px;
  overflow: hidden;
  transition: height .3s;
}*/
</style>
